#include <iostream>
#include <windows.h>
#include <locale>
#include <codecvt>

// 定义宽字符导出函数类型
typedef const wchar_t* (*AICoder_GenerateCodeW_func)(const wchar_t*);
typedef const wchar_t* (*AICoder_GetPluginInfoW_func)();
typedef bool (*AICoder_Initialize_func)();

// 宽字符串转换工具
std::string wstring_to_utf8(const std::wstring& str) {
    std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
    return conv.to_bytes(str);
}

std::wstring utf8_to_wstring(const std::string& str) {
    std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
    return conv.from_bytes(str);
}

int main() {
    // 设置控制台输出编码为UTF-8
    SetConsoleOutputCP(65001);
    std::locale::global(std::locale("en_US.UTF-8"));
    
    std::cout << "🧪 测试 AICoder 插件 (Unicode版本)..." << std::endl;
    
    HMODULE hDll = LoadLibrary("AICoder.dll");
    if (!hDll) {
        std::cout << "❌ 无法加载 AICoder.dll" << std::endl;
        return 1;
    }
    
    // 获取宽字符函数指针
    AICoder_Initialize_func initFunc = (AICoder_Initialize_func)GetProcAddress(hDll, "AICoder_Initialize");
    AICoder_GenerateCodeW_func genFuncW = (AICoder_GenerateCodeW_func)GetProcAddress(hDll, "AICoder_GenerateCode");
    AICoder_GetPluginInfoW_func infoFuncW = (AICoder_GetPluginInfoW_func)GetProcAddress(hDll, "AICoder_GetPluginInfo");
    
    if (!initFunc || !genFuncW || !infoFuncW) {
        std::cout << "❌ 无法获取插件函数" << std::endl;
        FreeLibrary(hDll);
        return 1;
    }
    
    std::cout << "✅ AICoder插件加载成功" << std::endl;
    
    // 显示插件信息（转换为UTF-8输出）
    const wchar_t* pluginInfo = infoFuncW();
    std::string infoStr = wstring_to_utf8(pluginInfo);
    std::cout << "插件信息: " << infoStr << std::endl;
    
    if (initFunc()) {
        std::cout << "✅ 插件初始化成功" << std::endl;
        
        // 测试中文代码生成
        std::wstring requirement = L"创建一个Hello World程序";
        const wchar_t* code = genFuncW(requirement.c_str());
        
        std::string codeStr = wstring_to_utf8(code);
        std::cout << "生成的代码:\n" << codeStr << std::endl;
        
        std::cout << "🎉 插件测试完成！中文显示正常！" << std::endl;
    } else {
        std::cout << "❌ 插件初始化失败" << std::endl;
    }
    
    FreeLibrary(hDll);
    return 0;
}
